import { defineStore } from 'pinia'
import type { RouteRecordRaw } from 'vue-router'
import { allRouter } from '@/router/index'
import { deepClone } from '@/utils/index'
import shouye from '@/assets/imgs/aside-img/shouye.png'
import { roleRouter } from '@/types/shimInterface'
import { mine } from '@/types/shimNamespace'

export default defineStore('localRouter', {
  state: () => ({

    // 用户权限
    USER_ROLE: <roleRouter>{},

    // 权限对应路由信息
    CURRENT_ROUTER: <RouteRecordRaw[]>[],

    // 缓存的模块
    CACHE_MODULES: <mine.sToArr<mine.recordTag>>{},

    // 缓存组
    CACHE_GROUP: <mine.recordTag[]>[]
  }),

  getters: {
    GET_CURRENT_ROUTER({ CURRENT_ROUTER }): RouteRecordRaw[] {
      return CURRENT_ROUTER
    },

    GET_USER_ROLE({ USER_ROLE }): roleRouter {
      return USER_ROLE
    },

    GET_RECORD_MODULES({ CACHE_GROUP }) {
      return CACHE_GROUP
    }
  },

  actions: {

    // 更新路由
    UPDATE_CURRENT_ROUTER() {
      this.CURRENT_ROUTER.length = 0

      // 开发环境
      if (import.meta.env.MODE === 'development') {

        const sliceNum = allRouter.findIndex(item => item.path === '/home')

        // 排除首个路由(用于重定向)
        const tempRouter = deepClone(allRouter.slice(sliceNum))

        for (const router of tempRouter) {
          if (router.path === '/home' && router.children) {
            router.children.length = 0
            break
          }
        }

        this.CURRENT_ROUTER = tempRouter

      } else {
        // 获取当前账户路由权限
        const localRole = <roleRouter>{
          '/img-module': {
            'text-to-img': ['one', 'two'],
            'mouse-track': ['third'],
            'particle': [],
            'audio-line': []
          },
          '/games': { snake: [] }
        }

        this.USER_ROLE = localRole

        const currentRoute = <RouteRecordRaw[]>[{
          path: '/home',
          component: () => import('@/layout/index.vue'),
          meta: {
            title: '首页',
            icon: shouye,
            index: 0
          }
        }]

        allRouter.forEach(router => {
          if (router.path in localRole && router.children?.length) {
            const localModule = deepClone<RouteRecordRaw>(router)
            currentRoute.push(localModule)

            const tempChild = <RouteRecordRaw[]>[]
            localModule.children = tempChild
            router.children.forEach(child => {
              if (child.path in localRole[router.path]) {
                tempChild.push(child)
              }
            })
          }
        })

        this.CURRENT_ROUTER = currentRoute
      }

    },

    // 记录缓存的组件
    RECORD_COMONENT(source: mine.recordTag, remove: boolean = false) {

      // 移除模块
      if (remove && this.CACHE_MODULES[source.parentName]) {

        this.CACHE_MODULES[source.parentName].splice( this.CACHE_MODULES[source.parentName].findIndex(v => v.name === source.name), 1 )

        if (this.CACHE_MODULES[source.parentName].length === 0) {
          delete this.CACHE_MODULES[source.parentName]
        }

        const tempIndex = this.CACHE_GROUP.findIndex(({ name }) => name === source.name)
        if (tempIndex > -1) {
          this.CACHE_GROUP.splice(tempIndex, 1)
        }
        return
      }

      // 添加模块
      if (this.CACHE_MODULES[source.parentName]) {
        for (const item of this.CACHE_MODULES[source.parentName]) {
          if (item.name === source.name) {
            return
          }
        }

        this.CACHE_MODULES[source.parentName].push(source)

      } else {
        this.CACHE_MODULES[source.parentName] = [source]
      }

      for (const item of this.CACHE_GROUP) {
        if (item.name === source.name) {
          return
        }
      }

      this.CACHE_GROUP.push(source)
    },

    // 关闭标签
    CLOSE_GROUP(state: 'self' | 'left' | 'right' | 'all', item: mine.recordTag | null) {

      if (state === 'self' && item) {
        this.RECORD_COMONENT(item, true)
        return
      }

      let tempArr: mine.recordTag[] = []

      const tempIndex = this.CACHE_GROUP.findIndex(({ name }) => name === item?.name)

      if (state === 'left' && tempIndex > 0) {
        if (tempIndex > 0) tempArr = this.CACHE_GROUP.slice(0, tempIndex)
      } else if (state === 'right') {
        if (tempIndex < this.CACHE_GROUP.length) tempArr = this.CACHE_GROUP.slice(tempIndex + 1, this.CACHE_GROUP.length)
      } else {
        tempArr = [...(this.CACHE_GROUP)]
      }

      if (tempArr.length) {
        for (const tag of tempArr) {
          this.RECORD_COMONENT(tag, true)
        }
      }

    }

  }
})
